/** @noSelf **/

export default class ItemUtil {


    /**
     * 遍历玩家 盟友的玩家组 包括判断的玩家自身
     * @param callback
     */
    static getAllItemFromUnit(unit: unit): item[] {
        let items: item[] = []
        for (let i = 0; i < 6; i++) {
            let item = UnitItemInSlot(unit, i)
            items[i] = item;
        }
        return items;
    }

    /**
     * 遍历玩家 盟友的玩家组 包括判断的玩家自身
     * @param unit
     */
    static getItemAndChargesFromUnit(unit: unit): { [id: string]: number } {
        let items: { [id: string]: number } = {}
        for (let i = 0; i < 6; i++) {
            let item = UnitItemInSlot(unit, i)
            let itemTypeStr = id2string(GetItemTypeId(item))
            let itemCharges = GetItemCharges(item);
            if (!itemCharges || itemCharges < 1) {
                itemCharges = 1;
            }
            //添加值
            let oldCharges = items[itemTypeStr]
            if (!oldCharges) {
                oldCharges = 0;
            }
            items[itemTypeStr] = oldCharges + itemCharges
        }
        return items;
    }

    static costItemChargesFromUnit(unit: unit, itemId: number, charges: number): number {
        let costCharges = 0//已经消耗的次数
        let needCostCharges = 0 //还需要消耗的次数
        for (let i = 0; i < 6; i++) {
            needCostCharges = charges - costCharges
            if (costCharges >= charges) {
                return costCharges
            }
            let item = UnitItemInSlot(unit, i)
            if (GetItemTypeId(item) != itemId) {
                continue
            }

            let itemCharges = GetItemCharges(item);
            if (!itemCharges || itemCharges < 1) {
                itemCharges = 1;
            }
            //消耗值
            if (itemCharges <= needCostCharges) {
                costCharges = costCharges + itemCharges
                RemoveItem(item)
            } else if (itemCharges > needCostCharges) {
                costCharges = costCharges + needCostCharges
                SetItemCharges(item, itemCharges - needCostCharges)
            }
        }
        return costCharges;
    }


}
